package com.example.helloworldtext2.holder;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.bumptech.glide.Glide;
import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.example.helloworldtext2.R;
import com.example.helloworldtext2.model.Article;
import com.example.helloworldtext2.utils.VideoPlayManager;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSource;
//import com.shuyu.gsyvideoplayer.GSYVideoManager;
//import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
//import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
//import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;


public class RecyclerItemNormalHolder extends RecyclerItemBaseHolder {

    public final static String TAG = "RecyclerItemNormalHolder";

    protected Context context = null;

//    StandardGSYVideoPlayer gsyVideoPlayer;
    TextView tvContent;

    ImageView imageView;

//    GSYVideoOptionBuilder gsyVideoOptionBuilder;
    private com.google.android.exoplayer2.ui.StyledPlayerView  playerView;
    private ImageView coverImage;
    private ImageView playButton;
    private SeekBar videoProgress;
    private TextView currentTimeText;
    private TextView totalTimeText;
    private RelativeLayout progressContainer;
    private TextView titleText;
    private TextView descriptionText;
    private TextView authorText;
    private ImageView likeButton;
    private TextView likeCount;
    private ImageView commentButton;
    private TextView commentCount;
    private ImageView collectButton;
    private ImageView shareButton;
    private ImageView userAvatar;
    private TextView videoDuration;
    private LinearLayout topicsContainerInner;
    private ExoPlayer player;
    private TextView follow;


    public RecyclerItemNormalHolder(Context context, View itemView) {
        super(itemView);
        playerView = itemView.findViewById(R.id.videoView);
        coverImage = itemView.findViewById(R.id.coverImage);
//        playButton = itemView.findViewById(R.id.playButton);
//        videoProgress = itemView.findViewById(R.id.videoProgress);
//        currentTimeText = itemView.findViewById(R.id.currentTimeText);
//        totalTimeText = itemView.findViewById(R.id.totalTimeText);
//        progressContainer = itemView.findViewById(R.id.progressContainer);
       titleText = itemView.findViewById(R.id.titleText);
        descriptionText = itemView.findViewById(R.id.descriptionText);
//        authorText = itemView.findViewById(R.id.authorText);
//        likeButton = itemView.findViewById(R.id.likeButton);
//        likeCount = itemView.findViewById(R.id.likeCount);
//        commentButton = itemView.findViewById(R.id.commentButton);
//        commentCount = itemView.findViewById(R.id.commentCount);
//        collectButton = itemView.findViewById(R.id.collectButton);
//        shareButton = itemView.findViewById(R.id.shareButton);
        userAvatar = itemView.findViewById(R.id.userAvatar);
////                videoDuration = itemView.findViewById(R.id.videoDuration);
//        // 正确初始化话题容器内部的LinearLayout
//        topicsContainerInner = itemView.findViewById(R.id.topicsContainerInner);
        follow = itemView.findViewById(R.id.follow);

        playerView.setUseController(false);
//        playerView.setShowRewindButton(false);
//        playerView.setShowFastForwardButton(false);
//        // 隐藏上一个和下一个按钮
//        playerView.setShowPreviousButton(false);
//        playerView.setShowNextButton(false);
        // 设置控制器不自动显示
//        playerView.setControllerAutoShow(false);
        playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH);
        // playerView监听是不是当前的播放选项
        
        this.context = context;
        // 添加视频区域点击事件监听器
        playerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 切换播放状态
                VideoPlayManager.getInstance(context).togglePlayback();
            }
        });
//        监听关注
        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,"点击关注", Toast.LENGTH_SHORT).show();
                view.setVisibility(View.GONE);
            }
        });


    }

    public void onBind(int position, Article article) {
        Glide.with(userAvatar).load(article.getAuthorAvatar()).circleCrop().into(userAvatar);
        titleText.setText("@" + article.getAuthorName());
        descriptionText.setText(article.getDescription());
        Glide.with(context).load(article.getCoverImageUrl()).into(coverImage);
//        authorText.setText(videoItem.getAuthorName());
//        likeCount.setText(String.valueOf(videoItem.getLikeCount()));
//        commentCount.setText(String.valueOf(videoItem.getCommentCount()));
//        Log.d("sfdadfsdf", article.getTitle());
//
//        // 初始化ExoPlayer
//        initPlayer(context);
//        // 设置视频URI
//        String videoUrl = article.getVideoUrl();
//        Log.d(TAG, "Video URL: " + videoUrl);
//
//        // 检查URL是否为空
//        if (videoUrl == null || videoUrl.isEmpty()) {
//            Log.e(TAG, "Video URL is null or empty");
//            Toast.makeText(context, "视频URL无效", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        Uri videoUri = Uri.parse(videoUrl);
//
//        // 创建带缓存的数据源工厂，使用同步块保护缓存访问
//        DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(context);
////        synchronized (cacheLock) {
////            if (simpleCache != null) {
////                dataSourceFactory = new CacheDataSource.Factory()
////                        .setCache(simpleCache)
////                        .setUpstreamDataSourceFactory(new DefaultDataSource.Factory(context));
////            }
////        }
//
//        // 根据URL扩展名选择合适的媒体源
//        MediaSource mediaSource;
//        if (videoUrl.toLowerCase().endsWith(".m3u8")) {
//            // 使用HLS媒体源处理M3U8流媒体
//            mediaSource = new HlsMediaSource.Factory(dataSourceFactory)
//                    .createMediaSource(MediaItem.fromUri(videoUri));
//        } else {
//            // 使用渐进式媒体源处理普通视频文件
//            mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
//                    .createMediaSource(MediaItem.fromUri(videoUri));
//        }
//
//        // 准备播放器
//        player.setMediaSource(mediaSource);
//        player.prepare();
//
//        // 视频准备好的监听器
//        player.addListener(new Player.Listener() {
//            @Override
//            public void onPlaybackStateChanged(int playbackState) {
//                if (playbackState == Player.STATE_READY) {
//                    // 视频准备完成后自动播放
////                    player.play();
////                    playButton.setVisibility(View.GONE);
////                    coverImage.setVisibility(View.GONE);
//
//                    // 设置总时间
////                    totalTimeText.setText(formatTime(player.getDuration()));
//
//                    // 开始更新进度条
////                    progressHandler.post(progressRunnable);
//                } else if (playbackState == Player.STATE_ENDED) {
//                    // 播放完成后重新开始播放
//                    player.seekTo(0);
//                    player.play();
//                }
//            }
//
//            @Override
//            public void onPlayerError(@NonNull com.google.android.exoplayer2.PlaybackException error) {
//                Log.e(TAG, "Player error: " + error.getMessage(), error);
//                Toast.makeText(context, "播放视频时出错: " + error.getMessage(), Toast.LENGTH_LONG).show();
//
//                // 显示播放按钮和封面图片
////                playButton.setVisibility(View.VISIBLE);
////                coverImage.setVisibility(View.VISIBLE);
//            }
//        });


    }

    // 格式化时间显示 (毫秒转为 mm:ss 格式)
    private String formatTime(long milliseconds) {
        int seconds = (int) (milliseconds / 1000);
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void initPlayer(Context context) {
        if (player == null) {
            player = new ExoPlayer.Builder(context).build();
            playerView.setPlayer(player);
            player.setRepeatMode(com.google.android.exoplayer2.Player.REPEAT_MODE_ONE);
        }
    }

    /**
     * 停止并释放播放器
     */
    public void stopPlayback() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    /**
     * 暂停播放
     */
    public void pausePlayback() {
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }
    /**
     * 开始播放
     */
    public void startPlayback() {
        if (player != null && !player.isPlaying()) {
            player.seekTo(0);
            player.play();
        }
    }

}